package com.echo.servlet.CommentServlet;

import com.echo.entity.User;
import com.echo.exception.CommentException;
import com.echo.service.CommentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 评论Servlet：处理评论相关的HTTP请求
 */
@WebServlet("/comment")
public class CommentServlet extends HttpServlet {
    private static final Logger logger = Logger.getLogger(CommentServlet.class.getName());
    private CommentService commentService;
    
    @Override
    public void init() throws ServletException {
        super.init();
        this.commentService = new CommentService();
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求参数
        String action = request.getParameter("action");
        
        // 默认操作是获取评论列表
        if (action == null || action.isEmpty()) {
            action = "list";
        }
        
        switch (action) {
            case "list":
                // 获取评论列表
                getCommentList(request, response);
                break;
            case "delete":
                // 删除评论
                deleteComment(request, response);
                break;
            default:
                // 未知操作
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "未知操作");
                break;
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求编码，防止中文乱码
        request.setCharacterEncoding("UTF-8");
        
        // 获取请求参数
        String action = request.getParameter("action");
        
        // 默认操作是添加评论
        if (action == null || action.isEmpty()) {
            action = "add";
        }
        
        switch (action) {
            case "add":
                // 添加评论
                addComment(request, response);
                break;
            default:
                // 未知操作
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "未知操作");
                break;
        }
    }
    
    /**
     * 添加评论
     */
    private void addComment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.info("处理添加评论请求");
        System.out.println("===== 开始处理添加评论请求 =====");
        
        // 将变量声明移到try块外部，使其在catch块中也可用
        String articleIdStr = null;
        Integer articleId = null;
        
        try {
            // 首先获取文章ID参数
            articleIdStr = request.getParameter("articleId");
            System.out.println("获取到的articleId参数值: " + articleIdStr);
            articleId = Integer.parseInt(articleIdStr);
            System.out.println("解析后的articleId: " + articleId);
            
            // 检查用户是否登录
            HttpSession session = request.getSession();
            // 尝试从session中获取用户信息，支持不同的属性名
            User currentUser = (User) session.getAttribute("loginUser");
            System.out.println("从loginUser属性获取用户: " + (currentUser != null ? currentUser.getNickname() : "null"));
            if (currentUser == null) {
                currentUser = (User) session.getAttribute("user");
                System.out.println("从user属性获取用户: " + (currentUser != null ? currentUser.getNickname() : "null"));
            }
            
            if (currentUser == null) {
                // 用户未登录，重定向到登录页并带上来源URL作为参数
                System.out.println("用户未登录，跳转到登录页");
                request.setAttribute("error", "请先登录再评论");
                // 将当前文章详情页的URL作为来源参数传递
                request.setAttribute("returnUrl", request.getContextPath() + "/article-detail?id=" + articleId);
                request.getRequestDispatcher("/login.html").forward(request, response);
                return;
            }
            
            // 获取其他评论参数
            String content = request.getParameter("content");
            String parentIdStr = request.getParameter("parentId");
            System.out.println("获取到的评论内容: " + content);
            System.out.println("获取到的parentId参数: " + parentIdStr);
            
            Integer parentId = null;
            if (parentIdStr != null && !parentIdStr.isEmpty()) {
                parentId = Integer.parseInt(parentIdStr);
                System.out.println("解析后的parentId: " + parentId);
            }
            
            // 调用服务层添加评论
            System.out.println("调用commentService.addComment()方法");
            int commentId = commentService.addComment(articleId, currentUser.getId(), content, parentId);
            System.out.println("评论添加成功，生成的评论ID: " + commentId);
            
            // 评论成功，重定向回文章详情页
            String redirectUrl = request.getContextPath() + "/article-detail?id=" + articleId;
            System.out.println("重定向到: " + redirectUrl);
            response.sendRedirect(redirectUrl);
            
        } catch (NumberFormatException e) {
            logger.log(Level.WARNING, "参数格式错误: " + e.getMessage(), e);
            // 即使有异常，也要重定向回文章详情页
            if (articleIdStr != null) {
                String redirectUrl = request.getContextPath() + "/article-detail?id=" + articleIdStr;
                System.out.println("参数错误，重定向到: " + redirectUrl);
                response.sendRedirect(redirectUrl);
            } else {
                // 如果没有文章ID，重定向到首页
                response.sendRedirect(request.getContextPath() + "/");
            }
        } catch (CommentException e) {
            logger.log(Level.WARNING, "添加评论失败: " + e.getMessage(), e);
            // 即使有异常，也要重定向回文章详情页
            String redirectUrl = request.getContextPath() + "/article-detail?id=" + articleId;
            System.out.println("评论失败，重定向到: " + redirectUrl);
            response.sendRedirect(redirectUrl);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "添加评论时发生未知错误: " + e.getMessage(), e);
            // 即使有异常，也要重定向回文章详情页
            if (articleId != null) {
                String redirectUrl = request.getContextPath() + "/article-detail?id=" + articleId;
                System.out.println("未知错误，重定向到: " + redirectUrl);
                response.sendRedirect(redirectUrl);
            } else if (articleIdStr != null) {
                String redirectUrl = request.getContextPath() + "/article-detail?id=" + articleIdStr;
                response.sendRedirect(redirectUrl);
            } else {
                // 如果没有文章ID，重定向到首页
                response.sendRedirect(request.getContextPath() + "/");
            }
        }
    }
    
    /**
     * 获取评论列表
     */
    private void getCommentList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.info("处理获取评论列表请求");
        
        try {
            // 获取文章ID和页码
            Integer articleId = Integer.parseInt(request.getParameter("articleId"));
            String pageStr = request.getParameter("page");
            
            Integer currentPage = 1;
            if (pageStr != null && !pageStr.isEmpty()) {
                currentPage = Integer.parseInt(pageStr);
            }
            
            // 调用服务层获取评论列表
            Map<String, Object> commentData = commentService.getCommentsByArticleId(articleId, currentPage);
            
            // 将评论数据设置到请求属性中
            request.setAttribute("comments", commentData.get("comments"));
            request.setAttribute("currentPage", commentData.get("currentPage"));
            request.setAttribute("totalPages", commentData.get("totalPages"));
            request.setAttribute("totalComments", commentData.get("totalComments"));
            request.setAttribute("pageSize", commentData.get("pageSize"));
            request.setAttribute("hasPrevious", commentData.get("hasPrevious"));
            request.setAttribute("hasNext", commentData.get("hasNext"));
            request.setAttribute("articleId", articleId);
            
            // 转发到评论列表页面（使用Thymeleaf模板）
            request.getRequestDispatcher("/article-detail.html").forward(request, response);
            
        } catch (NumberFormatException e) {
            logger.log(Level.WARNING, "参数格式错误: " + e.getMessage(), e);
            request.setAttribute("error", "参数错误，请稍后重试");
            request.getRequestDispatcher("/article-detail.html").forward(request, response);
        } catch (CommentException e) {
            logger.log(Level.WARNING, "获取评论列表失败: " + e.getMessage(), e);
            request.setAttribute("error", e.getMessage());
            request.getRequestDispatcher("/article-detail.html").forward(request, response);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "获取评论列表时发生未知错误: " + e.getMessage(), e);
            request.setAttribute("error", "获取评论列表失败，请稍后重试");
            request.getRequestDispatcher("/article-detail.html").forward(request, response);
        }
    }
    
    /**
     * 删除评论
     */
    private void deleteComment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.info("处理删除评论请求");
        
        try {
            // 首先获取评论ID和文章ID参数
            Integer commentId = Integer.parseInt(request.getParameter("id"));
            Integer articleId = Integer.parseInt(request.getParameter("articleId"));
            
            // 检查用户是否登录
            HttpSession session = request.getSession();
            // 尝试从session中获取用户信息，支持不同的属性名
            User currentUser = (User) session.getAttribute("loginUser");
            if (currentUser == null) {
                currentUser = (User) session.getAttribute("user");
            }
            
            if (currentUser == null) {
                // 用户未登录，重定向到登录页并带上来源URL作为参数
                request.setAttribute("error", "请先登录再删除评论");
                // 将当前文章详情页的URL作为来源参数传递
                request.setAttribute("returnUrl", request.getContextPath() + "/article-detail?id=" + articleId);
                request.getRequestDispatcher("/login.html").forward(request, response);
                return;
            }
            
            // 调用服务层删除评论
            commentService.deleteComment(commentId, currentUser.getId());
            
            // 删除成功，重定向回文章详情页
            response.sendRedirect(request.getContextPath() + "/article-detail?id=" + articleId);
            
        } catch (NumberFormatException e) {
            logger.log(Level.WARNING, "参数格式错误: " + e.getMessage(), e);
            request.setAttribute("error", "参数错误，请稍后重试");
            request.getRequestDispatcher("/article-detail.html").forward(request, response);
        } catch (CommentException e) {
            logger.log(Level.WARNING, "删除评论失败: " + e.getMessage(), e);
            request.setAttribute("error", e.getMessage());
            request.getRequestDispatcher("/article-detail.html").forward(request, response);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "删除评论时发生未知错误: " + e.getMessage(), e);
            request.setAttribute("error", "删除评论失败，请稍后重试");
            request.getRequestDispatcher("/article-detail.html").forward(request, response);
        }
    }
}